package hash;

public class BinarySearchTree {

    static class TreeNode{
        public int key;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    public void insert(int key){
        if(root == null){
            root = new TreeNode(key);
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if(key < cur.key){
                parent = cur;
                cur = cur.left;
            }else if(key > cur.key){
                parent = cur;
                cur = cur.right;
            }else{
                return;
            }
        }

        cur = new TreeNode(key);
        if(parent.key > key){
            parent.left = cur;
        }else{
            parent.right = cur;
        }

    }

    public void inorder(TreeNode root){
        if(root == null){
            return;
        }
        inorder(root.left);
        System.out.print(root.key+" ");
        inorder(root.right);
    }

    public boolean remove(int key){
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if(cur.key > key){
                parent = cur;
                cur = cur.left;
            }else if(cur.key == key){
                removeNode(parent,cur);
                return true;
            }else{
                parent = cur;
                cur = cur.right;
            }
        }
        return false;
    }

    public void removeNode(TreeNode parent,TreeNode cur){
        if(cur.left == null){
            if(cur == root){
                root = cur.right;
            }else if(cur == parent.left){
                parent.left = cur.right;
            }else{
                parent.right = cur.right;
            }
        }else if(cur.right == null){
            if(cur == root){
                root = cur.left;
            }else if(cur == parent.right){
                parent.right = cur.left;
            }else{
                parent.left = cur.left;
            }
        }else{
            TreeNode targetParent = cur;
            TreeNode target = cur.right;
            while(target.left != null){
                targetParent = target;
                target = target.left;
            }
            cur.key = target.key;
            targetParent.left = target.right;
            if(target == targetParent.left){
                targetParent.left = target.right;
            }else{
                targetParent.right = target.right;
            }
        }
    }
}
